package thinker.miracle.business.user.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import thinker.miracle.business.base.BaseController;
import thinker.miracle.business.common.entity.OptionTypeEntity;
import thinker.miracle.business.common.model.OptionTypeModel;
import thinker.miracle.business.common.service.OptionTypeService;
import thinker.miracle.business.user.entity.UserInfoEntity;
import thinker.miracle.business.user.entity.UserLoginLogEntity;
import thinker.miracle.business.user.model.UserInfoModel;
import thinker.miracle.business.user.service.UserInfoService;
import thinker.miracle.business.user.service.UserLoginLogService;
import thinker.miracle.commons.Result;
import thinker.miracle.rabbitmq.producer.MessageProducer;
import thinker.miracle.utils.BeanUtil;
import thinker.miracle.utils.Constants;
import thinker.miracle.utils.DateUtil;
import thinker.miracle.utils.MD5;
import thinker.miracle.utils.MathUtil;
import thinker.miracle.utils.ValidateUtil;

/**
 * @author bo.chen
 *
 */
@Controller
@RequestMapping("/user/userInfo")
public class UserInfoController extends BaseController {

	@Autowired
	UserInfoService userInfoService;
	
	@Autowired
	UserLoginLogService userLoginLogService;

	@Autowired
	OptionTypeService optionTypeService;
	
	@Autowired
	MessageProducer messageProducer;
	
	/**
	 * 注册
	 * 
	 * result.code 
	 * 				000 注册成功，
	 * 				001 手机号码不合法， 
	 * 				002 名称不合法， 
	 * 				003 密码不合法， 
	 * 				004 用户已经注册，
	 * 				998 其他异常
	 */
	@ResponseBody
	@RequestMapping(value = "/signUp", method = { RequestMethod.POST,RequestMethod.GET })
	public void signUp() {
		Result result = this.getResult();

		// String emial = getParameter("emial");
		String phone = getParameter("phone");
		String password = getParameter("password");
		String name = getParameter("name");

		try {
			if (!ValidateUtil.valiPhone(phone)) {// 验证手机号码
				result.setCode("001");
				writeJson(result);
				return;
			}
			if (!ValidateUtil.valiName(name)) {// 验证名称
				result.setCode("002");
				writeJson(result);
				return;
			}
			if (password == null || "".equals(password.trim())) {
				result.setCode("003");
				writeJson(result);
				return;
			}
			UserInfoEntity userInfo = userInfoService.getByPhone(phone);
			if (userInfo != null) {
				result.setCode("004");
				writeJson(result);
				return;
			}
			userInfo = new UserInfoEntity();
			userInfo.setPhone(phone);
			userInfo.setPassword(MD5.md5(password));
			userInfo.setName(name);
			userInfo.setVersion(MathUtil.random());
			userInfo.setCreateTime(DateUtil.getTime());
			userInfoService.save(userInfo);
			
			//生成tocken
			UserLoginLogEntity userLoginLog = new UserLoginLogEntity();
			userLoginLog.setUserId(userInfo.getId());
			userLoginLog.setIp(getIp());
			userLoginLog = userLoginLogService.restCreateTocken(userLoginLog);
			
			UserInfoModel userInfoModel = new UserInfoModel();
			BeanUtils.copyProperties(userInfo, userInfoModel);
			userInfoModel.setTocken(userLoginLog.getTocken());
			
			result.addData("userInfo", userInfoModel).success();
		} catch (Exception e) {
			logger.error("",e);
		}
		writeJson(result);
	}

	/**
	 * 登陆
	 * 
	 */
	@ResponseBody
	@RequestMapping(value = "/login", method = { RequestMethod.POST,RequestMethod.GET })
	public void login() {
		Result result = this.getResult();
		String phone = getParameter("phone");
		String password = getParameter("password");
		try {
			if (!ValidateUtil.valiPhone(phone)) {// 验证手机号码
				result.setCode("001");
				writeJson(result);
				return;
			}
			if (password == null || "".equals(password.trim())) {
				result.setCode("002");
				writeJson(result);
				return;
			}
			UserInfoEntity userInfo = userInfoService.loginVerify(phone,MD5.md5(password));
			if(userInfo != null){
				UserLoginLogEntity	userLoginLog = new UserLoginLogEntity();
				userLoginLog.setUserId(userInfo.getId());
				userLoginLog.setIp(getIp());
				userLoginLog = userLoginLogService.restCreateTocken(userLoginLog);
				//屏蔽关键信息
				UserInfoModel userInfoModel = new UserInfoModel();
				BeanUtils.copyProperties(userInfo, userInfoModel);
				userInfoModel.setTocken(userLoginLog.getTocken());
				
				result.addData("userInfo", userInfoModel).success();
			}else{
				result.setCode("003");
				writeJson(result);
			}
			result.success();
		} catch (Exception e) {
			logger.error("",e);
		}
		writeJson(result);
	}

	
	/**
	 * 修改用户信息
	 */
	@ResponseBody
	@RequestMapping(value="/putUserInfo",method={RequestMethod.POST,RequestMethod.GET})
	public void putUserInfo(){
		Result result = this.getResult();
		String tocken  = getParameter("tocken");
		String name = getParameter("name");//名称
		String sex = getParameter("sex");//性别
		String height = getParameter("height");//身高
		String weight = getParameter("weight");//体重
		String birthday = getParameter("birthday");//出生日期
		String emotion = getParameter("emotion");//情感状态
		String industry = getParameter("industry");//行业
		String income = getParameter("income");//收入
		String interest = getParameter("interest");//兴趣
		String sign = getParameter("sign");//签名
		
		try{
			//验证所有数据都不为空
			if(ValidateUtil.empty(name,sex,height,height,weight,
					birthday,emotion,industry,income,income,
					interest,sign
					)){
				result.setCode("001");
				writeJson(result);
				return;
			}
			//验证性别必须正确
			if(!(sex == null && ("0".equals(sex) &&!"1".equals(sex)))){
				result.setCode("002");
				writeJson(result);
				return;
			}
			//验证身高必须为数字
			if(! ValidateUtil.valiNumber(height)){
				result.setCode("003");
				writeJson(result);
				return;
			}
			//验证体重必须为数字
			if(!ValidateUtil.valiNumber(weight)){
				result.setCode("004");
				writeJson(result);
				return;
			}
			//验证生日必须为日期格式
			if(!ValidateUtil.valiDateTime(birthday)){
				result.setCode("005");
				writeJson(result);
				return;
			}
			//验证个性签名不得超过200个字
			if(!ValidateUtil.valiLength(sign, 200)){
				result.setCode("006");
				writeJson(result);
				return;
			}
			
			//根据tocken查询用户
			UserInfoEntity userInfo = userInfoService.getByTocken(tocken);
			if(userInfo == null){
				result = Result.tockenVerifiedFailed();
				writeJson(result);
				return;
			}
			
			String id = userInfo.getId();
			String version = userInfo.getVersion();
			userInfo = new UserInfoEntity();
			userInfo.setId(id);
			userInfo.setVersion(version);
			userInfo.setName(name);
			userInfo.setSex(sex);
			userInfo.setHeight(height);
			userInfo.setWeight(weight);
			userInfo.setBirthday(birthday);
			userInfo.setEmotion(emotion);
			userInfo.setIndustry(industry);
			userInfo.setIncome(income);
			userInfo.setInterest(interest);
			userInfo.setSign(sign);
			userInfo.setUpdateTime(DateUtil.getTime());
			userInfoService.save(userInfo);
			
			UserInfoModel userInfoModel = new UserInfoModel();
			BeanUtils.copyProperties(userInfo, userInfoModel);
			userInfoModel.setTocken(tocken);
			
			result.addData("userInfo", userInfoModel).success();
		}catch(Exception e){
			logger.error("",e);
		}
		writeJson(result);
	}
	
	
	/**
	 * 上传用户图标
	 * 
	 * @param request
	 * @param response
	 * @param tocken
	 */
	@ResponseBody
	@RequestMapping(value="/putUserIco",method={RequestMethod.POST})
	public void putUserIco(HttpServletRequest request,
			HttpServletResponse response,String tocken) {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());  
        Result result = this.getResult();
        String path = "";
        try{
	        if(multipartResolver.isMultipart(request)){  
	            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;  
	            Iterator<String> iter = multiRequest.getFileNames();  
	            while(iter.hasNext()){  
	                MultipartFile file = multiRequest.getFile(iter.next());  
	                if(file != null){  
	                    String name = file.getOriginalFilename();
	                    if(!ValidateUtil.valiImage(name)){
	                    	result.setCode("002");
	        				writeJson(result);
	                    	return;
	                    }
	                    if(name != null && !"".equals(name.trim())){  
	                        String fileName = MathUtil.random() + name;//重新生成文件名称
	                        path = Constants.ROOT + Constants.USER_ICO + fileName;
	                        File localFile = new File(path);  
	                        file.transferTo(localFile);
	                        //存放文件
	                        UserInfoEntity userInfo = userInfoService.getByTocken(tocken);
	                        UserInfoEntity userInfoEntity = new UserInfoEntity();
	                        userInfoEntity.setId(userInfo.getId());
	                        userInfoEntity.setIco(Constants.USER_ICO+fileName);
	                        userInfoEntity.setUpdateTime(DateUtil.getTime());
	                        userInfoService.save(userInfoEntity);
	                        
	                        result.addData("ico", Constants.USER_ICO+fileName).success();
	                    }
	                }
	            }  
	        }
        }catch(Exception e){
        	logger.error("",e);
        	//删除原来文件
        	File file = new File(path);
        	if(file.exists())
        		file.delete();
        }
        writeJson(result);
	}
	
	
	/**
	 * 获取用户信息选择项
	 * 情感状态
	 * 行业
	 * 收入
	 * 兴趣
	 */
	@ResponseBody
	@RequestMapping(value="/getUserInfoSelect",method={RequestMethod.POST,RequestMethod.GET})
	public void getUserInfoSelect(){
		Result result = this.getResult();
		//emotion:情感状态,industry:行业,income:收入,interest:兴趣
		String optionTypeNo = getParameter("optionTypeNo");
		try{
			List<OptionTypeEntity> optionTypes = new ArrayList<OptionTypeEntity>();
			if(!ValidateUtil.empty(optionTypeNo)){
				optionTypes = optionTypeService.getByOptionTypeNo(optionTypeNo);
			}
			List<OptionTypeModel> options = new ArrayList<OptionTypeModel>();
			options = BeanUtil.copyPropertiesList(optionTypes, OptionTypeModel.class);
			result.addData("options", options).success();
		}catch(Exception e){
			logger.error("",e);
		}
		writeJson(result);
	}
	
	
	/**
	 * 下载用户图标
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/getUserIco",method={RequestMethod.POST,RequestMethod.GET})
	public ResponseEntity<byte[]> getUserIco(){
		String tocken = getParameter("tocken");
		File file = null;
		try{
			UserInfoEntity userInfo = userInfoService.getByTocken(tocken);
			String path = Constants.get(null) +  userInfo.getIco();
			file = new File(path);
			if(!file.exists()){
				
			}
		}catch(Exception e){
			logger.error("",e);
		}
		return this.download(file, null);
	}
	
	@ResponseBody
	@RequestMapping(value="/testSendMessage",method={RequestMethod.POST,RequestMethod.GET})
	public Result testSendMessage(){
		Result result = this.getResult().defeat();
		try{
			messageProducer.sendMessage("测试message");
			result.success();
		}catch(Exception e){
			logger.error("",e);
		}
		return result;
	}
}
